package com.example.breathinglight

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startBreathing(2000)
    }

    private fun startBreathing(duration: Long) {
        val increaseBrightnessAnimator = ValueAnimator.ofInt(1, 255)
        val decreaseBrightnessAnimator = ValueAnimator.ofInt(255, 1)
        increaseBrightnessAnimator.duration = duration
        increaseBrightnessAnimator.addUpdateListener { setBrightness(it.animatedValue as Int) }
        increaseBrightnessAnimator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                decreaseBrightnessAnimator.start()
            }
        })

        decreaseBrightnessAnimator.duration = duration
        decreaseBrightnessAnimator.addUpdateListener { setBrightness(it.animatedValue as Int) }
        decreaseBrightnessAnimator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                increaseBrightnessAnimator.start()
            }
        })

        increaseBrightnessAnimator.start()
    }

    /**
     * 调整app级别屏幕亮度（不修改全局屏幕亮度）
     */
    private fun setBrightness(brightnessValue: Int) {
        val lp = window.attributes
        lp.screenBrightness = brightnessValue / 255.0f
        window.attributes = lp
    }
}